package test.enba.mongodb.controller;

import com.enba.boot.mongodb.MongoOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import test.enba.mongodb.doc.MyEntityDoc;
import test.enba.mongodb.repository.MyEntityDocRepository;

@RestController
@RequestMapping("/mongo")
public class MongoController {

  @Autowired private MongoOperator mongoOperator;
  @Autowired private MyEntityDocRepository repository;

  @GetMapping("/insert")
  public MyEntityDoc insert() {
    MyEntityDoc myEntity = new MyEntityDoc("aaa111", "bbb111", "123456");
    mongoOperator.insert(myEntity);
    return myEntity;
  }

  @GetMapping("/delete")
  public String delete(@RequestParam String id) {
    mongoOperator.delete(MyEntityDoc.class, id);
    return "删除成功";
  }

  @GetMapping("/update")
  public MyEntityDoc update(@RequestParam String id) {
    return mongoOperator.update(MyEntityDoc.class, id, new Update().set("test", "aaa333"));
  }

  @GetMapping("/find")
  public MyEntityDoc find(@RequestParam String id) {
    return mongoOperator.findById(MyEntityDoc.class, id);
  }

  //  ========================== repository方式 ==========================

  @GetMapping("/repository-insert")
  public MyEntityDoc repositoryInsert() {
    MyEntityDoc myEntity = new MyEntityDoc("enba", "niuniuniu", "888");
    repository.insert(myEntity);
    return myEntity;
  }

  @GetMapping("/repository-delete")
  public String repositoryDelete(@RequestParam String id) {
    repository.deleteById(id);
    return "删除成功";
  }

  @GetMapping("/repository-update")
  public MyEntityDoc repositoryUpdate() {
    return repository.save(new MyEntityDoc("enba222", "niuniuniu666", "888"));
  }

  @GetMapping("/repository-find")
  public MyEntityDoc repositoryFind(@RequestParam String id) {
    return repository.findById(id).get();
  }
}
